package com.zy.cat.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zy.cat.common.utils.TJKUtils;
import com.zy.cat.dao.Dao;
import com.zy.cat.entity.dev.CatDevOrderInfo;
import com.zy.cat.entity.dev.CatDevReRedHistory;
import com.zy.cat.entity.dev.CatDevUserInfo;
import com.zy.cat.entity.dev.repository.CatDevReRedHistoryRepository;
import com.zy.cat.entity.dev.resp.CatDevOrderResp;
import com.zy.cat.entity.dev.resp.CatDevReRedHistoryResp;
import com.zy.cat.entity.dev.resp.CatDevRebateInfoResp;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.service.CacheService;
import com.zy.cat.service.CatDevService;
import com.zy.cat.service.CatOrderService;
@Service
public class CatOrderServiceImpl implements CatOrderService {
	
	@Autowired
	private Dao<CatDevOrderResp> orderDao;
	
	@Autowired
	private Dao<CatDevOrderInfo> orderInfoDao;
	
	@Autowired
	private Dao<CatDevRebateInfoResp> rebateInfoRespDao;
	
	@Autowired
	private Dao<CatDevReRedHistoryResp> catDevReRedHistoryRespDao;
	
	@Autowired
	private CacheService cacheService;
	
	@Autowired
	private CatDevService catDevService;
	
	@Autowired
	private CatDevReRedHistoryRepository catDevReRedHistoryRepository;
	

	@Override
	public ResultPage<CatDevOrderResp> list(String pid, int dstatus,int otype, Pages pages) {
		return orderDao.listAndPages(new CatDevOrderResp(pid, dstatus,otype), "getOrderList", pages);
	}

	@Override
	public Boolean addOrder(String pid, String tid,String date) {
        CatDevOrderInfo catDevOrderInfo = orderInfoDao.selectOne(new CatDevOrderInfo(tid), "getTkOrder");
        
        if (catDevOrderInfo==null) {
			catDevOrderInfo=new CatDevOrderInfo(tid);
			catDevOrderInfo.setFoid(tid);
			catDevOrderInfo.setCtime(date);
			catDevOrderInfo.setSicon("-");
			catDevOrderInfo.setSid("-");
			catDevOrderInfo.setSname("-");
		}
        
        
		//设置用户ID
		catDevOrderInfo.setPid(pid);
		catDevOrderInfo.setTtime(TJKUtils.DateTime());
		//类型为手动填单
		catDevOrderInfo.setDtype(0);
		//订单设置为失效状态
		catDevOrderInfo.setDstatus(0);
		if(orderInfoDao.insert(catDevOrderInfo)==false) {
			return false;
		}
		return true;
	}

	@Override
	public CatDevOrderResp getOrderById(String tid) {
		return orderDao.selectOne(new CatDevOrderResp(tid),"getOrderById");
	}

	@Override
	public Integer getFavoritesType(Integer rtype, String pid) {
		//查看用户商品购买次数
		Integer userOrderNumber = cacheService.getUserOrderNumber(pid);
		//如果没有下单过15元补贴的订单则展示15元购,反之展示3元购
		return userOrderNumber==null || userOrderNumber==0?15:3;
	}

	@Override
	public List<CatDevOrderResp> getBackOrderList(String pid) {
		return orderDao.list(CatDevOrderResp.builder().pid(pid).build(), "getBackOrderList");
	}

	@Override
	@Transactional
	public ResultPage<CatDevReRedHistoryResp> getBackCashList(String pid, Integer fstatus,Pages pages) {
		//如果分页为空则设置默认值
		if (pages==null) {
			pages.setPageNum(1);
			pages.setPageSize(20);
		}else if (pages.getPageNum()<=0 || pages.getPageSize()<=0) {
			pages.setPageNum(1);
			pages.setPageSize(20);
		}
		ResultPage<CatDevReRedHistoryResp> resultPage;
		//如果查询为待使用列表,则更新已过期的返现红包状态
		if (fstatus==0) {
			resultPage=new ResultPage<>(pages.getPageNum(), pages.getPageSize());
			//如果为未使用状态的红包则判断红包是否已过期
			List<CatDevReRedHistory> list = catDevReRedHistoryRepository.findByPidAndFstatus(pid, fstatus);
			if (list!=null) {
				for (CatDevReRedHistory catDevReRedHistory : list) {
					boolean after = TJKUtils.parse2LocalDateTime(catDevReRedHistory.getCtime()).plusDays(1).isAfter(LocalDateTime.now());
					if (!after) {
						//将此红包归为过期红包
						catDevReRedHistory.setFstatus(2);
					}
				}
				List<CatDevReRedHistoryResp> respList = list.stream().filter(his->his.getFstatus()==0).map(mapper->{
					return JSON.parseObject(JSON.toJSONString(mapper), CatDevReRedHistoryResp.class);
				}).collect(Collectors.toList());
				resultPage.setList(respList);
			}
			//当前已无可用返现红包,新增一个
			if (resultPage.getList()==null || resultPage.getList().size()<1) {
				//判断是否已有15元补贴的订单，如果含有15元补贴的订单则创建3元返利红包，反之创建15返利红包
				Integer orderNumber = cacheService.getUserOrderNumber(pid);
				CatDevReRedHistory redHistory;
				if (orderNumber==null) {
					redHistory = catDevReRedHistoryRepository.saveAndFlush(new CatDevReRedHistory(pid,TJKUtils.DateTime(),0,2,1500,TJKUtils.DateTime()));	
				}else {
					redHistory = catDevReRedHistoryRepository.saveAndFlush(new CatDevReRedHistory(pid,TJKUtils.DateTime(),0,0,300,TJKUtils.DateTime()));
				}
				if (redHistory!=null) {
					CatDevReRedHistoryResp object = JSON.parseObject(JSON.toJSONString(redHistory), CatDevReRedHistoryResp.class);
					resultPage.setList(Arrays.asList(object));
				}
			}
		}else {
			resultPage = catDevReRedHistoryRespDao.listAndPages(new CatDevReRedHistoryResp(pid, fstatus), "findByPidAndFstatus", pages);
		}
		return resultPage;
	}

	@Override
	public Boolean receiveBackCash(String pid) {
		//判断是否已有15元补贴的订单，如果含有15元补贴的订单则创建3元返利红包，反之创建15返利红包
		Integer orderNumber = cacheService.getUserOrderNumber(pid);
		CatDevReRedHistory redHistory;
		if (orderNumber==null) {
			redHistory = catDevReRedHistoryRepository.saveAndFlush(new CatDevReRedHistory(pid,TJKUtils.DateTime(),0,2,1500,TJKUtils.DateTime()));	
		}else {
			redHistory = catDevReRedHistoryRepository.saveAndFlush(new CatDevReRedHistory(pid,TJKUtils.DateTime(),0,0,300,TJKUtils.DateTime()));
		}
		return redHistory!=null?true:false;
	}

	@Override
	public boolean promoteRebate(String pid, String oid) {
		if (StringUtils.isEmpty(oid)) {
			return false;
		}
		CatDevOrderInfo info = orderInfoDao.selectOne(new CatDevOrderInfo(oid), "selectOrder");
		//计算提升返利+10%之后50%返利,返利金额
		info.setLtime(TJKUtils.DateTime());
		long yincome=(info.getYincome()*5/2)/2;
		info.setYincome(yincome);
		long sincome=(info.getSincome()*5/2)/2;
		info.setSincome(sincome);
		info.setRate(50);
		info.setPstatus(1);
		return orderInfoDao.update(info, "updateIncreaseRebate");
	}

	@Override
	public CatDevRebateInfoResp getRebateInfo(String pid) {
		//查询用户订单返利数据
		CatDevRebateInfoResp resp = rebateInfoRespDao.selectOne(CatDevOrderResp.builder().pid(pid).build(), "getOrderRebateInfo");
		return resp;
	}
}
